﻿using AuthenticationServer.Data.Identity.Entities;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Extensions;

using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace AuthenticationServer.Services
{

    public class CustomProfileService : IProfileService
    {
        protected readonly ILogger Logger;
        private readonly IUserStore<User> _userRepository;
        private readonly UserManager<User> _userManager;

        public CustomProfileService(IUserStore<User> userRepository,
            UserManager<User> userManager,
            ILogger<CustomProfileService> logger)
        {
            _userManager = userManager;
            _userRepository = userRepository;
        }
        public Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            //throw new NotImplementedException();
            //try
            //{
            //    //depending on the scope accessing the user data.
            //    var claims = context.Subject.Claims.ToList();
            //    //set issued claims to return
            //    context.IssuedClaims = claims.ToList();
            //}
            //catch (Exception ex)
            //{                //log your error
            //}

            var sub = context.Subject.GetSubjectId();
            var user = _userManager.FindByIdAsync(sub);

            var claims = new Claim[]
            {
                new Claim("foo", "bar")
            };
            //claims.Concat(context.Subject.Claims);
            //context.AddRequestedClaims(claims.Concat(context.Subject.Claims));

            //if (context.RequestedClaimTypes.Any())
            //{
            //    context.IssuedClaims.AddRange(context.FilterClaims(claims.Concat(context.Subject.Claims)));
            //}
            //else
            //{
            //    context.IssuedClaims.AddRange(claims.Concat(context.Subject.Claims));
            //}
            context.IssuedClaims.AddRange(claims.Concat(context.Subject.Claims));

            return Task.CompletedTask;
        }

        public Task IsActiveAsync(IsActiveContext context)
        {
            context.IsActive = true;
            return Task.CompletedTask;
        }
    }
}
